package transaction

import (
	"encoding/json"
	"strings"

	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/rwsetutil"
	putil "github.com/hyperledger/fabric/protoutil"
)

func getRWSet(envelope *common.Envelope) (*string, error) {
	action, err := putil.GetActionFromEnvelopeMsg(envelope)
	if err != nil {
		g.Log().Errorf("%v", err)
		return nil, err
	}
	txRWSet := &rwsetutil.TxRwSet{}
	err = txRWSet.FromProtoBytes(action.Results)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("  |---> rwset:\n%v\n", txRWSet)

	ss := g.Export(txRWSet)
	//ss = strings.ReplaceAll(ss, "\t", "")
	//ss = strings.ReplaceAll(ss, "\n", "")
	j1, err := gjson.LoadJson(ss)
	if err != nil {
		return nil, err
	}
	j2 := j1.GetJson("NsRwSets")
	if err != nil {
		return nil, err
	}
	ss = j2.Export()
	ss = strings.ReplaceAll(ss, "\t", "")
	ss = strings.ReplaceAll(ss, "\n", "")

	return &ss, nil
}

func Struct2JsonStr(v interface{}) string {
	b, err := json.Marshal(v)
	if err != nil {
		return "nil"
	}
	return string(b)
}
